package com.scuvc.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class ConnectionFactory {
    //这是德鲁伊连接池对象
    private static DruidDataSource ds;
    private static Connection conn;
    static{
        Properties pops = new Properties();
        try {
            pops.load(ConnectionFactory.class.getResourceAsStream("jdbc.properties"));
            ds = (DruidDataSource) DruidDataSourceFactory.createDataSource(pops);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static DruidDataSource getDruidDataSource(){
        return ds;
    }
    public static Connection getConnection(){
        try {
            conn = ds.getConnection();
            return conn;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
    //封装开启/关闭事务事务
    public static void setAutoCommit(boolean flag,Connection connection){
        try {
            connection.setAutoCommit(flag);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    //关闭Connection连接资源
    public static void close(Connection connection){
        try {
            if(connection!=null && !connection.isClosed()){
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    //回滚事务
    public static void rollback(Connection connection){
        try {
            connection.rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    //提交事务
    public static void commit(Connection connection){
        try {
            connection.commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
